package pers.wk.queues.temp;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import pers.wk.config.MQConfig;
import pers.wk.utils.MQConnectionUtils;

import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;

/**
 * 临时队列
 * 之前我们创建的队列都是指定名称的，我们需要指定消费者去消费那个队列的消息；
 * 但是，有时我们希望当我们连接 RabbitMQ 的时候，自动为我们创建一个 随机名称的队列 ，
 * 当我们断开消费者的连接时，队列将被自动删除。
 */
public class TempQueueTest {

    public static void main(String[] args) {
        //1.ConnectionFactory
        ConnectionFactory connectionFactory = MQConnectionUtils.getConnectionFactory("/");
        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接
            connection = connectionFactory.newConnection();
            //3.通过连接获取通道Channel
            channel = connection.createChannel();

            //创建临时队列
            String queueName = channel.queueDeclare().getQueue();
            System.out.println("临时队列-生产者启动。。。");

            int read = System.in.read();
            String msg = "hello world " + read;


            //5.发送消息
            //exchange为空，但是会有一个默认的交换机
            channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());
            System.out.println("临时队列-生产者发送消息：" + msg);

            //临时队列消费者
            //自动应答
            channel.basicConsume(queueName, true, (consumerTag, message) -> {
                System.out.println("consumerTag = " + consumerTag);
                //@FunctionalInterface DeliverCallback
                System.out.println(MessageFormat.format("临时队列-消费者获取消息：【{1}】{0}",
                        new String(message.getBody(), StandardCharsets.UTF_8)
                        , message.getEnvelope().getDeliveryTag()));
            }, (consumerTag) -> {
                //@FunctionalInterface CancelCallback
            });

            System.in.read();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MQConnectionUtils.close(connection, channel);
        }

    }
}
